jQuery(function ($) {
	var $container = $('#avatar-upload-container'),
		params = {},
		//csrfParam = $('meta[name=csrf-param]').attr('content'),
		//csrfToken = $('meta[name=csrf-token]').attr('content'),
		uploader;
		params['csrfmiddlewaretoken'] = $container.parents('form').find('input[name=csrfmiddlewaretoken]').val();
        console.log(params);
		uploader = new plupload.Uploader({
			runtimes: 'html5',
			browse_button: 'avatar-file', // you can pass in id.
			container: $container.get(0), // ... or DOM Element itself
			max_file_size: '2mb',
			file_data_name: 'avatar',
			multi_selection: false,
			url: "/accounts/avatar",
			multipart_params: params,
			filters: [
				{title: "Image files", extensions: "jpg,gif,png"},
			],

			init: {
				FilesAdded: function (up, files) {
					$container.find('.loading').show();
					$container.parents('.form-group').removeClass('has-error has-success');
					$container.find('.help-block-error').html('');
					uploader.start();
				},

				UploadProgress: function (up, file) {

				},

				FileUploaded: function (up, file, data) {
					var response;
					try {
						response = $.parseJSON(data.response);
					} catch (e) {
						uploadError('头像上传失败');
						return;
					}
					if (!response.success) {
						uploadError(response.message);
					} else {
						$container.find('.loading').hide();
						$container.find('.preview img').attr('src', response.avatar);
						$container.parents('.form-group').addClass('has-success');
					}
				},

				Error: function (up, err) {
					uploadError(err.message);
				}
			}
		});

	uploader.init();

	function uploadError(error) {
		$container.find('.loading').hide();
		$container.parents('.form-group').addClass('has-error');
		$container.find('.help-block-error').html(error);
	}
});